package com.dobest.studentmanagement.service;

import com.dobest.studentmanagement.dao.StuManagerRepository;
import com.dobest.studentmanagement.domain.StuManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * @Package: com.dobest.studentmanagement.service
 * @author: Jounghu
 * @date: 2018/8/26 22:17
 * @version: V1.0
 */
@Service
public class UserDetailService implements UserDetailsService {

    @Autowired
    StuManagerRepository stuManagerRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        StuManager stuManager = stuManagerRepository.findByUsername(username);
        if (stuManager != null && stuManager.getId() > 0 && !StringUtils.isEmpty(stuManager.getRoleName())) {
            // 存在此用户，进行拼接角色权限信息
            return new User(stuManager.getUsername(), stuManager.getPassword(), AuthorityUtils.createAuthorityList(stuManager.getRoleName()));
        }
        return null;
    }
}
